package com.example.design.patterns.geekbang.创建型.单例模式.explain.双重检测;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 双重检测模式: 既支持延迟加载、又支持高并发的单例实现方式
 */
public class IdGenerator {
    private static volatile IdGenerator instance;
    private AtomicLong id = new AtomicLong(0);

    private IdGenerator() {
    }

    public static IdGenerator getInstance() {
        if (instance == null) {
            synchronized (IdGenerator.class) { // 此处为类级别的锁
                if (instance == null) {
                    instance = new IdGenerator();
                }
            }
        }
        return instance;
    }

    public long getId() {
        return id.incrementAndGet();
    }
}
